#!/bin/bash

# SPDX-FileCopyrightText: 2021-2022 The Manyverse Authors
#
# SPDX-License-Identifier: CC0-1.0

function cleanUp {
  if ps -p $(cat appium-server.pid)> /dev/null; then
    kill -KILL $(cat appium-server.pid)
  fi
  rm appium-server.pid
  rm appium.log

  if ps -p $(cat syncserver.pid)> /dev/null; then
    kill -KILL $(cat syncserver.pid)
  fi
  rm syncserver.pid
  rm syncserver.log
}

set -eEu -o pipefail
shopt -s extdebug
IFS=$'\n\t'
trap 'onFailure $?' ERR
trap cleanUp EXIT

function onFailure() {
  echo "Unhandled script error $1 at ${BASH_SOURCE[0]}:${BASH_LINENO[0]}" >&2
  exit 1
}

pushd android/app/build/outputs/apk/indie/release
cp app-indie-release.apk app-indie-release-e2e.apk
popd
cd test/benchmark/sync-server && npm install > /dev/null 2>&1 && cd ../..
adb uninstall io.appium.settings > /dev/null 2>&1 || true
adb uninstall io.appium.uiautomator2.server > /dev/null 2>&1 || true
adb uninstall io.appium.uiautomator2.server.test > /dev/null 2>&1 || true
node test/benchmark/sync-server 1> syncserver.log 2> syncserver.log & echo $! > syncserver.pid
$(npm bin)/appium --port 4995 > appium.log & echo $! > appium-server.pid
sleep 5
$(npm bin)/tape test/benchmark/index.js | $(npm bin)/faucet
